#!/bin/bash

# Set the path of openssl executable and pyclaes installation path
OPENSSL=/usr/bin/openssl
GNUPLOT=/usr/bin/gnuplot

#PYCLAES_PATH=$WORKDIR/pyclaes/pyclaes/
PYCLAES_PATH=../pyclaes
PYCLAES=./pyclaes.py
PYCLAES_PARAMS="--profiling --overlap"
#PYCLAES_PARAMS="--profiling"

DATA_TEMPLATE=data_template
DATE=$(date "+%d-%m-%y_%H:%M:%S")
#DATA=data_$DATE
#PLOT=plot_$DATE
DATA=data.dat
PLOT=plot
PLOT_PNG=./plot.png

KEY=foo__bar__foobar

# Generate files containing random bytes with different size
for len in 16 64 256 1024 2048 4096 8192 16384 32768 65536 131072 262144 \
           524288 1048576 2097152 4194304 8388608 16777216 33554432 \
           67108864 134217728; do
  echo "Generating file with random bytes of size $len"
  #$OPENSSL rand -out /tmp/test$len $len
done


# Prepare plotting files
cp $DATA_TEMPLATE $DATA
cp $DATA_TEMPLATE openssl_$DATA

# Launch the encryption for each previously generated file
for len in 16 64 256 1024 2048 4096 8192 16384 32768 65536 131072 262144 \
           524288 1048576 2097152 4194304 8388608 16777216 33554432 \
           67108864 134217728; do

  pushd $PYCLAES_PATH
  $PYCLAES $PYCLAES_PARAMS $KEY /tmp/test$len /tmp/enc_test$len|\
           awk 'BEGIN{FS="\n"}\
               {if (match($0, "size: [0-9]+"))\
                  { size=substr($0, RSTART+6, RLENGTH-6) }\
                if (match($0, "throughput: ~[0-9]+.[0-9]+"))\
                  { througput=substr($0, RSTART+13, RLENGTH-13)}\
               }\
               END{ print size, througput }'>/tmp/tmp_enc
  popd
  cat /tmp/tmp_enc>>$DATA
done

# Get openssl speed
#$OPENSSL speed -evp aes-128-ecb | tail -n 2 |\
#         awk 'BEGIN{RS=" ";i=0;j=0}\
#                /[0-9]+\.[0-9]+k/{thrg[i]=$1;sub(/k/,"",thrg[i]); i++}\
#                /^[0-9]+$/{len[j]=$1; j++}\
#              END{for(k=0;k<i;k++) print len[k], thrg[k]*1000}'>>openssl_$DATA

# Plot data
$GNUPLOT $PLOT

# Rename files
mv $PLOT_PNG plot_$DATE.png
mv $DATA data_$DATE.dat
#mv openssl_$DATA openssl_$DATA_$DATE.dat

rm /tmp/tmp_enc
exit 0
